use chrono::{Datelike, NaiveDateTime, Timelike};
use std::path::PathBuf;

use tokio::fs;

use once_cell::sync::Lazy;

pub const UPLOAD_FILE_PATH: Lazy<String> = Lazy::new(|| match dotenv::var("UPLOAD_FILE_PATH") {
    Ok(fp) => fp,
    Err(_) => dotenv::var("upload_path").expect("Failed to get upload_path"),
});

pub const FILE_MAX_SIZE: i32 = 8192;

pub async fn ensure_dir_exists(ts: NaiveDateTime) -> Result<String, String> {
    dotenv::dotenv().ok();
    let year = ts.year().to_string();
    let mm = ts.month().to_string();
    let dd = ts.day().to_string();
    let hh = ts.hour().to_string();
    let abs_dir = format!("{year}/{mm}/{dd}/{hh}");

    let dir_path = PathBuf::from(UPLOAD_FILE_PATH.as_str())
        .join(year)
        .join(mm)
        .join(dd)
        .join(hh);

    if !dir_path.exists() {
        fs::create_dir_all(&dir_path)
            .await
            .map_err(|err| format!("Failed to create directory: {}", err))?;
    }
    Ok(abs_dir)
}
